import os
import time

import numpy as np
from PIL import Image
from django.http import StreamingHttpResponse

from ai_mode.yolo import YOLO
import cv2
from django.shortcuts import render, redirect

# Create your views here.
from django.shortcuts import render, HttpResponse
from django.http import StreamingHttpResponse


from djangoProject import settings
from ai_mode.predict import predict
from ai_mode.video import Video


def index(request):
    return render(request, 'index.html')

def result_2(request):
    return  render(request, 'result_2.html')

# 处理图片
def files(request):
    if request.POST:
        # 由前端指定的name获取到图片数据
        img = request.FILES.get('img')
        # 获取图片的全文件名
        img_name = img.name
        # 截取文件后缀和文件名
        mobile = os.path.splitext(img_name)[0]
        ext = os.path.splitext(img_name)[1]
        # 重定义文件名
        img_name = f'avatar-{mobile}{ext}'
        img_s = f'result-{mobile}{ext}'

        # 从配置文件中载入图片保存路径
        img_path = os.path.join(settings.IMG_UPLOAD, img_name)
        img_path1 = os.path.join(settings.IMG_UPLOAD, img_s)

        path = "D:\\PycharmProjects\\djangoProject\\static\\uploads\\"
        if os.path.exists(path + img_s):
           os.remove(path + img_s)
        # 写入文件
        with open(img_path, 'ab') as fp:
            # 如果上传的图片非常大，就通过chunks()方法分割成多个片段来上传
            for chunk in img.chunks():
                fp.write(chunk)
        with open(img_path1, 'ab') as fp:
            # 如果上传的图片非常大，就通过chunks()方法分割成多个片段来上传
            for chunk in img.chunks():
                fp.write(chunk)
        predict(img_s)
        # D:\\PycharmProjects\\djangoProject
        file_name = "\\static\\uploads" + '\\' + img_name
        file_name_s = "\\static\\uploads" + '\\' + img_s
        return render(request, 'result_1.html', {'avatar_img': file_name, 'result_img': file_name_s})
    else:
        return HttpResponse("请返回首页！")

"""
    视频流路由。将其放入img标记的src属性中。
    例如：<img src='https://ip:port/uri' >
    if ret：
     # frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
"""
# 处理视频
def video(request):
    # 视频流相机对象
    camera = cv2.VideoCapture(0)
    return StreamingHttpResponse(gen_display(camera), content_type='multipart/x-mixed-replace; boundary=frame')

def gen_display(camera):
    """
    视频流生成器功能。
    """
    yolo = YOLO()
    while True:
        # 读取图片
        ret, frame = camera.read()

        # 检测视频
        t1 = time.time()
        # 读取某一帧
        fps=0.0
        # 格式转变，BGRtoRGB
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        # 转变成Image
        frame = Image.fromarray(np.uint8(frame))
        # 进行检测
        frame = np.array(yolo.detect_image(frame))
        # RGBtoBGR满足opencv显示格式
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        # 每秒传输帧数计算，此时的time.time()表示检测完后的时间
        fps = (fps + (1. / (time.time() - t1))) / 2
        # print("fps= %.2f" % (fps))
        frame = cv2.putText(frame, "fps= %.2f" % fps, (0, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

        if ret:
            # 将图片进行解码
            ret, frame = cv2.imencode('.jpeg', frame)
            if ret:
                # 转换为byte类型的，存储在迭代器中
                yield (b'--frame\r\n'
                       b'Content-Type: image/jpeg\r\n\r\n' + frame.tobytes() + b'\r\n')




